package org.groupg.project.docvarinit.services;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import javafx.application.Platform;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.sax.BodyContentHandler;
import org.groupg.project.docvarinit.model.ExecuteFileType;
import org.groupg.project.docvarinit.model.FileProperty;
import org.groupg.project.docvarinit.model.MainModel;
import org.groupg.project.docvarinit.model.enums.MainFileTypeEnums;
import org.groupg.project.docvarinit.utils.MainFileUtils;
import org.groupg.project.docvarinit.utils.TextUtils;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainServices {

    static final String regex = "\\$\\{([^}]+)\\}";

    static final Pattern pattern = Pattern.compile(regex);


    static Log log = LogFactory.get();



    public static List<FileProperty> getAllFilePropertyByFile(MainModel mainModel, ProgressBar progressBar, Label progressLabel) {
        List<FileProperty> fileProperties = new ArrayList<FileProperty>();
        log.debug("开始处理路径【"+mainModel.getSourceDir().toPath()+"】");
        List<String> propertyNames = new ArrayList<>();
        List<File> files = MainFileUtils.listFiles(mainModel.getSourceDir());
        int sum = files.size();
        for (int i = 0; i < files.size(); i++) {
            File f = files.get(i);
            int finalI = i;
            log.debug("处理["+(i+1)+"/"+sum+"]个文件：["+mainModel.getSourceDir().toPath().relativize(f.toPath())+"]");
            Platform.runLater(() -> {
                progressBar.setProgress((double) (finalI + 1) /sum);
                progressLabel.setText("处理["+(finalI+1)+"/"+sum+"]个文件：["+mainModel.getSourceDir().toPath().relativize(f.toPath())+"]");
            });
            Matcher matcher = pattern.matcher(f.getAbsolutePath().substring(mainModel.getSourceDir().toString().length()));
                while (matcher.find()) {
                    String propertyName = matcher.group(1);
                    System.out.println(matcher.group(1)); // 输出每个捕获组中的内容
                    if (!propertyNames.contains(propertyName)) {
                        log.debug("在路径中找到名字找到属性名称：【{}】",propertyName);
                        propertyNames.add(propertyName);
                        fileProperties.add(new FileProperty(propertyName, ""));
                    }
                }
            try (InputStream stream = new FileInputStream(f)) {
                // 自动检测文件类型的解析器
                AutoDetectParser parser = new AutoDetectParser();
                // 用于存储解析出的文本内容
                BodyContentHandler handler = new BodyContentHandler();
                // 用于存储文件的元数据
                Metadata metadata = new Metadata();
                // 解析文件
                parser.parse(stream, handler, metadata);
                // 获取解析出的文本内容
                String text = handler.toString();

                matcher = pattern.matcher(text);
                while (matcher.find()) {
                    String propertyName = matcher.group(1);
                    System.out.println(matcher.group(1)); // 输出每个捕获组中的内容
                    if (!propertyNames.contains(propertyName)) {
                        log.debug("找到属性名称：【{}】",propertyName);
                        propertyNames.add(propertyName);
                        fileProperties.add(new FileProperty(propertyName, ""));
                    }
                }
            } catch (IOException | SAXException | TikaException e) {
                log.error(e.getMessage(), e);
            }
        }
        Platform.runLater(() -> {
                progressBar.setProgress(1.0);
                progressLabel.setText("加载完成！");
            });
        propertyNames.clear();
        return fileProperties;
    }

    public static void coverAllFiles(MainModel model, ProgressBar progressBar, Label progressLabel) throws IOException {

        // todo 还未完成复制文件并将对应内容替换掉的过程。
        for (File sourcefile : model.getFiles()) {
            String tempFilePath = sourcefile.getAbsolutePath().replace(model.getSourceDir().getAbsolutePath(),model.getOutputDir().getAbsolutePath());
            tempFilePath = model.getSubstitutor().replace(tempFilePath);
            File targetfile = new File(tempFilePath);
            MainFileTypeEnums.getFileType(targetfile).coverFile(sourcefile,targetfile,model);
        }

    }
}
